#!/usr/bin/env python
# -*- coding:utf-8 -*-

import sys
import requests
import json
import os
import shutil
from scpy.logger import get_logger
logger = get_logger(__file__)

reload(sys)
sys.setdefaultencoding("utf-8")

base_url = 'http://192.168.31.116:7003'


def get_from_ours(key, province='', forcedLatest=''):
    url = ''
    if province != '' and forcedLatest != '':
        url = url = base_url + '/saic?key=%s&province=%s&forcedLatest=%s' % (key, province, forcedLatest)
    elif province != '':
        url = base_url + '/saic?key=%s&province=%s' % (key, province)
    else:
        url = base_url + '/saic?key=%s' % key

    return requests.get(url, timeout=100000).text


def get_from_qcc(key, province='', forcedLatest=''):
    url = ''
    if province != '' and forcedLatest != '':
        url = url = base_url + '/qichacha?key=%s&province=%s&forcedLatest=%s' % (key, province, forcedLatest)
    elif province != '':
        url = base_url + '/qichacha?key=%s&province=%s' % (key, province)
    else:
        url = base_url + '/qichacha?key=%s' % key
    return requests.get(url).text


def print_dict(f, d):
    for i in d:
        print>>f, i, d[i]


def print_list(f, l):
    for i in l:
        if isinstance(i, dict):
            print_dict(f, i)
        elif isinstance(i, list):
            print_list(f, i)
        else:
            print>>f, i


def check(key, province='', forcedLatest=''):
    from check_share_holder_list import check_share_holder_list
    from check_basic_list import check_basic_list
    from check_person_list import check_person_list
    from check_entinvItemList import check_entinvItemList
    from check_alterList import check_alter_list
    from check_yearReportList import check_year_report_list

    text = None
    try:
        text = get_from_ours(key, province, forcedLatest)
        print text
        a = json.loads(text)
    except Exception, e:
            logger.exception('json load error from crawler, print content:\n%s', text)

    try:
        text = get_from_qcc(key, province, forcedLatest)
        b = json.loads(text)
    except Exception, e:
            logger.exception('json load error from qcc, print content:\n%s', text)

    path = u'/'.join(['./result', key_]) + u'/'
    # print path
    if os.path.exists(path):
        # 直接删除非空文件夹
        shutil.rmtree(path)
        # os.rmdir(path)
    os.mkdir(path)

    with open(path + 'check_result', 'w') as f:
        if not check_basic_list(key, a['basicList'][0], b['basicList'][0]):
            print>>f, 'basic list: not ok'

        try:
            if not check_share_holder_list(key, a['shareHolderList'], b['shareHolderList']):
                print>>f, 'share holder list: not ok'
        except Exception, e:
            logger.exception('structure error')

        try:
            if not check_person_list(key, a['personList'], b['personList']):
                print>>f, 'person list: not ok'
        except Exception, e:
            logger.exception('structure error')

        try:
            if not check_entinvItemList(key, a['entinvItemList'], b['entinvItemList']):
                print>>f, 'entinvItemList: not ok'
        except Exception, e:
            logger.exception('structure error')

        try:
            if not check_alter_list(key, a['alterList'], b['alterList']):
                print>>f, 'alterList: not ok'
        except Exception, e:
            logger.exception('structure error')

        try:
            if not check_year_report_list(key, a['yearReportList'], b['yearReportList']):
                print>>f, 'yearReportList: not ok'
        except Exception, e:
            logger.exception('structure error')


if __name__ == '__main__':
    # key_ = u'重庆猪八戒网络有限公司'

    # key_ = u'上海互加文化传播有限公司'

    key_ = u'利诚（四川）服装有限公司'

    # key_ = u'湖南华菱钢铁集团有限责任公司'
    # key_ = u'华菱控股集团有限公司'

    # key_ = u'黑龙江省电力有限公司'

    # key_ = u'云南中豪置业有限责任公司'
    check(key_)

